<template>
  <div class="varable-manage">
    <div class="pcocess-config__center">
      <div class="process-config-wrap">
        <div class="title">全局字段可用于客户、工单、动态表单等模块，提高不同业务场景下的协同效率</div>
        <div style="margin-bottom: 12px">
          <span class="icon-text" @click.stop="exportAct('add')"><i class="el-icon-plus"></i>添加</span>
          <!-- <span class="icon-text" @click.stop="exportAct('refresh')"><i class="iconfont icon-shuaxin"></i>刷新</span> -->
          <el-input
            :style="{ width: '200px' }"
            placeholder="请输入字段名称"
            size="mini"
            class="condition"
            v-model="form.name"
          >
          </el-input>
          <el-select
            size="mini"
            v-model="form.type"
            clearable
            multiple
            placeholder="请选择字段类型"
            style="margin: 0px 16px"
          >
            <el-option v-for="(item, index) in fieldTypes" :label="item.label" :value="item.value" :key="index">
            </el-option>
          </el-select>
          <el-select size="mini" v-model="form.status" clearable placeholder="请选择字段状态">
            <el-option label="启用" :value="1"> </el-option>
            <el-option label="停用" :value="0"> </el-option>
          </el-select>
          <el-button type="primary" style="margin-left: 16px" size="mini" @click.stop="handleCurrentChange(1)">查询</el-button>
        </div>
        <el-table :data="tableList" size="mini" style="width: 100%">
          <el-table-column prop="name" label="字段名称" :show-overflow-tooltip="true"> </el-table-column>
          <el-table-column prop="type" label="字段类型">
            <template scope="scope">
              <span>{{ typeAllMap[scope.row.type] }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间">
            <template scope="scope">
              <span v-if="scope.row.category === 'system'">系统预置</span>
              <span v-else>{{ scope.row.updateTime }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="updateAgent" label="更新人">
            <template scope="scope">
              <span v-if="scope.row.category === 'system'">系统预置</span>
              <span v-else>{{ scope.row.updateAgent }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template scope="scope">
              <el-switch
                :disabled="scope.row.category === 'system'"
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="changeStatus(scope.row)"
                inline-prompt
              />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template scope="scope">
              <span class="edit-btn main-color" @click.stop="handleEdit(scope.row)">{{ $t('public.edit') }}</span>
              <span class="del-btn" v-if="scope.row.category !== 'system'" @click.stop="deleteField(scope.row)">{{
                $t('public.delete')
              }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="clearfix" style="margin-top: 16px;">
      <el-pagination
      class="fr"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagingData.page"
      :page-sizes="[10, 20, 50]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagingData.total || 0">
    </el-pagination>
    </div>
      </div>
    </div>
    <addEditField ref="addEditField" @updateSuccess="updateSuccess"></addEditField>
  </div>
</template>
<script>
import { typeArr, typeAllMap } from './utils/utils.js'
import addEditField from './components/addEditField.vue'
import { cloneDeep } from 'lodash'
export default {
  name: 'variableManage',
  data() {
    return {
      fieldTypes: typeArr('all'),
      pagingData: { page: 1, total: 0, limit: 10 },
      form: {
        status: '',
        type: [],
        name: ''
      },

      count: 0,
      typeAllMap: typeAllMap,
      tableList: []
    }
  },
  components: {
    addEditField
  },
  methods: {
    handleCurrentChange (page) {
      this.pagingData.page = page
      this.fetchData()
    },
    handleSizeChange(size){
      this.pagingData.limit = size
      this.pagingData.page = 1
      this.fetchData()
    },
    updateSuccess() {
      this.fetchData()
    },
    deleteField(data) {
      this.$confirm(`请确认要删除该字段？`, this.$t('public.tip'), {
        confirmButtonText: this.$t('public.confirm'),
        cancelButtonText: this.$t('public.cancel'),
        cancelButtonClass: 'primary_btn',
        confirmButtonClass: 'primary_btn',
        type: 'warning'
      }).then(() => {
        console.log(data)
        let dataNew = {
          field: data.field
        }
        this.$store.dispatch('delGlobalFieldById', dataNew).then((res) => {
          if (res && res.success) {
            this.$message.success('删除字段成功')
            this.handleCurrentChange(1)
          } else {
            this.$message.error('删除字段失败')
          }
        })
      })
    },
    changeStatus(data) {
      const str = data.status ? `请确认是否启用该字段?` : `请确认是否停用该字段？停用后，引用该字段的功能位置会将该字段删除（不影响历史日志）`
      this.$confirm(str, this.$t('public.tip'), {
        confirmButtonText: this.$t('public.confirm'),
        cancelButtonText: this.$t('public.cancel'),
        cancelButtonClass: 'primary_btn',
        confirmButtonClass: 'primary_btn',
        type: 'warning'
      }).then(() => {
        console.log(data)
        let dataNew = {
          field: data.field,
          status: data.status
        }
        this.$store.dispatch('updateGlobalFieldById', dataNew).then((res) => {
          if (res && res.success) {
            this.$message.success('修改状态成功')
            this.fetchData()
          } else {
            this.$message.error('修改状态失败')
          }
        })
      }).catch(() => {
        data.status = data.status ? 0 : 1
      })
    },
    //        添加刷新生效方法接收
    exportAct(val) {
      if (val === 'add') {
        this.$refs.addEditField.openDialog('add', {})
      } else if (val === 'refresh') {
        this.reshList()
      }
    },
    fetchData() {
      const { name, status, type } = this.form
      let data = {
        name,
        type,
        limit: this.pagingData.limit,
        page: this.pagingData.page
      }
      if (status === 0 || status === 1) {
        data.status = status
      }
      this.$store.dispatch('getGlobalField', data).then((resp) => {
        if (resp && resp.success) {
          this.pagingData.total = resp.data.count || 0
          let agentsAll = this.$store.getters.agents || {}
          this.tableList = (resp.data.list || []).map((item) => {
            item.updateAgent = agentsAll[item.updateAgent]
              ? agentsAll[item.updateAgent].displayName + '[' + agentsAll[item.updateAgent].exten + ']'
              : '-'
            return item
          })
        }
      })
    },
    reshList() {
      this.fetchData()
    },
    handleEdit(row) {
      this.$refs.addEditField.openDialog('edit', cloneDeep(row))
    }
  },
  beforeMount() {
    this.fetchData()
  }
}
</script>

<style lang="stylus" scoped>
.icon-text
  margin-right 16px
  cursor pointer
  line-height 30px
  i {
    color: #459ae9;
    font-size: 12px;
    margin-right: 2px;
  }
.varable-manage
  padding: 20px;
  height: calc(100vh - 95px);
  overflow-y: auto;
  font-size: 12px;
  .edit-btn
    margin-left: 10px
  .title
    color #3b5998
    height 30px
    line-height 30px
    padding 3px 10px
    overflow hidden
    text-overflow ellipsis
    max-width 100%
    white-space nowrap
    cursor pointer
  .margin-t-15
    margin-top 15px
  .margin-l-10
    margin-left 10px
  .pag-wapper
    position: absolute;
    right: 15px;
    top: 14px;
  .del-btn
    cursor pointer
    color: #ff6b6b
    margin-left 10px
  .main-color
    color #459ae9
    cursor pointer
  .wapper
    display flex
    flex-direction column
  .tool
    position relative
    border 1px solid #e7e7eb
    border-bottom 0
    padding  12px 15px
    /*display flex*/
    justify-content space-between
  .primary_btn
    padding 0px 10px
    min-width 60px
  .del
    color #ff6b6b
</style>
